import React from 'react';
import { Button, Radio, Modal, Checkbox, message } from 'antd';
import { connect } from 'react-redux';
import * as routerActions from 'react-router-redux';
import Api from 'Utils/api';
import { BROWSER_MODE } from 'Constants/webConstants';
import RightSide from 'Page/Components/RightSideImg';
import SubmitModal from './SubmitModal';
import { logout } from '../../../../actions/userAction';
import FlagTitle from '../../FlagTitle';
import './index.scss';

const confirm = Modal.confirm;
const RadioGroup = Radio.Group;
const CheckboxGroup = Checkbox.Group;
let answerArr = [];
class ExamDetail extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
    };
    this.returnHandle = ::this.returnHandle;
    this.handleSubmit = ::this.handleSubmit;
    this.handleModalOk = ::this.handleModalOk;
    this.renderMulti = ::this.renderMulti;
  }
  componentWillMount() {
    this.initData();
  }
  initData() {
    const api = new Api({
      method: 'GET',
      path: `/choices/user/${this.props.testID}`,
      success: (json) => {
        this.setState({
          data: json
        });
      },
      error: (msg) => {
        message.error(msg, 3);
      }
    });
    api.run();
  }
  returnHandle() {
    this.props.dispatch(logout());
    this.props.dispatch(routerActions.goBack());
  }
  handleSubmit() {
    const self = this;
    const sortAnswer = answerArr.sort((a, b) => a.questionNum > b.questionNum);
    const answer = [];
    for (let i = 0, len = sortAnswer.length; i < len; i++) {
      const list = sortAnswer[i].choice;
      const item = {
        biaoti: sortAnswer[i].questionId,
        answer: list,
      };
      answer.push(item);
    }
    confirm({
      title: '提交测评',
      content: '确认提交本次食安知识测评？',
      onOk() {
        self.submitModal.showModal(answer);
      },
      onCancel() {},
    });
  }
  handleModalOk() {
    this.props.dispatch(logout());
    this.props.dispatch(routerActions.goBack());
  }
  handleChoice(e) {
    if (answerArr.length === 0) {
      answerArr.push(e.target.value);
    } else {
      const newAW = answerArr.filter(item => item.questionNum !== e.target.value.questionNum);
      newAW.push(e.target.value);
      answerArr = [...newAW];
    }
  }
  onMultiChange(checkedValues) {
    if (checkedValues.length === 0) {
      answerArr = [];
      return;
    }
    if (answerArr.length === 0) {
      const answer = this.mergeMultiChoice(checkedValues);
      answerArr.push(answer);
    } else {
      const newAW = answerArr.filter(item => item.questionNum !== checkedValues[0].questionNum);
      const answer = this.mergeMultiChoice(checkedValues);
      newAW.push(answer);
      answerArr = [...newAW];
    }
  }
  mergeMultiChoice(checkedValues) {
    const choiceArr = [];
    for (let i = 0, len = checkedValues.length; i < len; i++) {
      choiceArr.push(checkedValues[i].choice);
    }
    const item = { choice: choiceArr, questionId: checkedValues[0].questionId, questionNum: checkedValues[0].questionNum };
    return item;
  }
  renderTest(data) {
    const nodeInfo = [];
    for (let i = 0, len = data.length; i < len; i++) {
      nodeInfo.push((
        <div className="exam-detail-item" key={i}>
          <div className="exam-detail-title">
            {
              `${i + 1}、${data[i].question}(${data[i].question_type})`
            }
          </div>
          <div className="exam-detail-choice">
            {
              data[i].question_type === '多选题' ?
                <CheckboxGroup onChange={this.onMultiChange.bind(this)} >
                  {
                    this.renderMulti && this.renderMulti(data[i], i + 1)
                  }
                </CheckboxGroup>
                :
                <RadioGroup onChange={this.handleChoice.bind(this)}>
                  {
                    this.renderKeys && this.renderKeys(data[i], i + 1)
                  }
                </RadioGroup>
            }
          </div>
        </div>
      ));
    }
    return nodeInfo;
  }
  renderMulti(item, questionNum) {
    const choice = ['A', 'B', 'C', 'D', 'E', 'F'];
    const keyInfo = [];
    for (let i = 0, len = item.all_option.length; i < len; i++) {
      keyInfo.push((
        <Checkbox
          key={i}
          value={{ choice: choice[i], questionId: item.id, questionNum: questionNum }}
        >
          {`${choice[i]}、${item.all_option[i]}`}
        </Checkbox>
      ));
    }
    return keyInfo;
  }
  renderKeys(item, questionNum) {
    const choice = ['A', 'B', 'C', 'D', 'E', 'F'];
    const keyInfo = [];
    const options = item.all_option ? item.all_option : [];
    for (let i = 0, len = options.length; i < len; i++) {
      keyInfo.push((
        <Radio
          key={i}
          value={{ choice: [choice[i]], questionId: item.id, questionNum: questionNum }}
          className="radio-vertical"
        >
          {`${choice[i]}、${item.all_option[i]}`}
        </Radio>
    ));
    }
    return keyInfo;
  }
  render() {
    const { mode } = this.props;
    const isVertical = BROWSER_MODE.isVertical(mode);
    return (
      <div className={`${isVertical ? 'v-' : ''}exam-detail-page`}>
        <div className="exam-detail-wrap">
          <FlagTitle className="exam-title" text="食安知识测评" />
          <div className="question-wrap">
            <div className="exam-detail-items">
              {
                this.renderTest && this.renderTest(this.state.data)
              }
            </div>
            <div className="exam-detail-submit">
              <Button onClick={this.handleSubmit} className="btn-submit">提交</Button>
            </div>
          </div>
        </div>
        {
          isVertical ? '' : <RightSide />
        }
        <SubmitModal
          ref={(ref) => {
            if (ref) {
              this.submitModal = ref.getWrappedInstance();
            }
          }}
          handleModalOk={this.handleModalOk}
        />
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    ...state.routing,
    ...state.userReducer,
    ...state.webReducer
  };
}
export default connect(mapStateToProps)(ExamDetail);
